<template>
    <view class="order-page">
        <!-- 顶部标签 -->
        <view class="tabs">
            <view v-for="(t, i) in tabs" :key="i" class="tab-item" :class="{ active: currentTab === t.key }"
                @click="changeTab(t.key)">
                {{ t.label }}
            </view>
        </view>
        <view style="height: 46px;"></view>
        <!-- 列表 -->
        <scroll-view class="list" scroll-y>
            <view v-for="(order, idx) in orderList" :key="idx" class="order-card">
                <view class="order-header"  @click="goOrderDetail(order)">
                    <text class="order-no">订单号:{{ getOrderNo(order) }}</text>
                    <text class="order-status">{{ getOrderStatusText(order) }}</text>
                </view>

                <view v-for="(g, gi) in getGoodsList(order)" :key="gi" class="good-row">
                    <image :src="formatImg(g.img || g.image)" mode="aspectFill" class="good-img" @click="goOrderDetail(order)"/>
                    <view class="good-main">
                        <view @click="goOrderDetail(order)">
                            <!-- 第一行：名称 | 价格 -->
                            <view class="line line-1">
                                <view class="good-title">{{ g.title || g.name }}</view>
                                <view class="good-price">¥ {{ (g.price || g.money) }}</view>
                            </view>
                            <!-- 第二行：描述 | 数量 -->
                            <view class="line line-2">
                                <view class="good-sub">{{ g.spec || g.norm || '' }}</view>
                                <view class="good-num">×{{ g.num || g.quantity || 1 }}</view>
                            </view>
                            <!-- 第三行：下单时间  -->
                            <view class="line line-3">
                                <text class="order-time">下单时间：{{ getOrderTime(order) }}</text>
                            </view>
                        </view>
                        <!-- 第四行 操作按钮 -->
                        <view class="btns">
                            <view class="btn ghost">删除订单</view>
                            <view class="btn refund">退款/售后</view>
                            <view class="btn primary" @click="reBuy(g)">再次购买</view>
                        </view>
                    </view>
                </view>
            </view>
            <view style="height: 50px;"></view>
            <view v-if="!loading && orderList.length === 0" class="empty">暂无订单</view>
            <view v-if="loading" class="loading">加载中...</view>
        </scroll-view>
    </view>

</template>

<script>
import { orderApi } from '@/api/indexAPI.js';
import { public_img } from '@/static/public.js';

export default {
    data() {
        return {
            tabs: [],
            currentTab: 'all',
            orderList: [],
            loading: false
        };
    },
    onLoad(options) {
        // 从我的页面带入的筛选参数
        const key = options?.status;
        if (key) {
            this.currentTab = key;
        } else {
            this.currentTab = 'all';
        }
    },
    onShow() {
        this.reload();
    },
    methods: {
        changeTab(key) {
            if (this.currentTab === key) return;
            this.currentTab = key;
            this.reload();
        },
        reload() {
            this.orderList = [];
            this.fetchList();
        },
        async fetchList() {
            this.loading = true;
            try {
                const status = this.currentTab === 'all' ? undefined : this.currentTab;
                const res = await orderApi.getOrderList(status);
                let list = [];
                if (res && res.code === 1) {
                    // 首屏同步服务端 tabs
                    if (res.data && Array.isArray(res.data.tabs)) {
                        this.tabs = res.data.tabs.map(t => ({
                            key: (t.status === null || t.status === undefined) ? 'all' : String(t.status),
                            label: t.name
                        }));
                        // 若 currentTab 不在新 tabs 中，重置为第一个
                        if (!this.tabs.find(t => t.key === this.currentTab)) {
                            this.currentTab = this.tabs[0]?.key || 'all';
                        }
                    }
                    list = Array.isArray(res.data?.list) ? res.data.list : [];
                }
                // 直接覆盖，无分页
                this.orderList = list;
            } catch (e) {
                console.error('获取订单列表失败', e);
            } finally {
                this.loading = false;
            }
        },

        // 工具方法：数据兼容
        getOrderNo(order) {
            return order.code || order.order_no || order.orderSn || order.orderNum || order.sn || '';
        },
        getOrderTime(order) {
            return order.createtime || order.create_time || order.createTime || order.time || '';
        },
        getOrderStatusText(order) {
            if (order.status_title) return order.status_title;
            const s = String(order.status ?? '');
            const map = {
                '1': '待付款',
                '2': '待发货',
                '3': '已发货',
                '4': '待评价',
                '6': '退款中',
                '7': '待退款',
                '8': '已取消'
            };
            return map[s] || '';
        },
        getGoodsList(order) {
            // 后端返回的是“每条订单一件商品”的扁平结构，组装为数组以复用 UI
            if (order && (order.title || order.img)) {
                return [{
                    img: order.img,
                    title: order.title,
                    spec: order.norm,
                    price: order.price,
                    num: order.num,
                    id: order.goods_id
                }];
            }
            if (Array.isArray(order.goods)) return order.goods;
            if (Array.isArray(order.items)) return order.items;
            if (order.good) return [order.good];
            // 兜底空数组
            return [];
        },
        formatImg(img) {
            if (!img) return public_img + '/img/placeholder.png';
            return img.startsWith('http') ? img : (public_img + img);
        },
        reBuy(g) {
            const productId = g.id;
            if (!productId) {
                uni.showToast({ title: '缺少商品ID，无法跳转', icon: 'none' });
                return;
            }
            uni.navigateTo({
                url: `/pages/product/index?id=${productId}`
            });
        },
        goOrderDetail(order) {
            // 跳转订单详情，仅样式展示，透传必要字段
            uni.navigateTo({
                url: '/pages/check/detail',
                success(res) {
                    res.eventChannel.emit('orderDetail', { order });
                }
            });
        }
    }
};
</script>

<style lang="scss" scoped>
.order-page {
    min-height: 100vh;
}

.tabs {
    display: flex;
    gap: 20px;
    background-color: #ffffff;
    justify-content: center;
    position: fixed;
    width: 100%;
    z-index: 100;
}

.tab-item {
    padding: 10px 6px;
    font-size: 15px;
    color: #9b9b9b;
}

.tab-item.active {
    color: #000;
    font-weight: 700;
    position: relative;
}

.order-card {
    margin: 10px 5px;
    padding: 10px 0;
    border-radius: 8px;
    background: #fff;
    box-shadow: 0 0 0 1px #f0f0f0 inset;
}

.order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 6px 12px 10px 12px;
}

.order-no {
    font-size: 14px;
    color: #333;
}

.order-status {
    font-size: 13px;
    color: #ff6a00;
}

.good-row {
    display: flex;
    padding: 10px 12px;
    border-top: 1px solid #f0f0f0;
}

.good-img {
    width: 90px;
    height: 90px;
    border-radius: 6px;
    background: #f7f7f7;
    margin-right: 10px;
}

.good-main {
    flex: 1;
    display: flex;
    flex-direction: column;
}

.line {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.good-title {
    font-size: 15px;
    color: #333;
}

.good-sub {
    margin-top: 6px;
    font-size: 13px;
    color: #999;
}


.line-1 .good-price {
    font-size: 15px;
    color: #000000;
}

.line-2 .good-num {
    font-size: 13px;
    color: #999;
    margin-left: 8px;
}

.line-3 {
    margin-top: 20px;
}

.order-footer {
    padding: 8px 12px 0 12px;
}

.order-time {
    font-size: 13px;
    color: #999;
}

.btns {
    margin-top: 10px;
    display: flex;
    justify-content: space-between;
}

.btn {
    padding: 2px 7px;
    border-radius: 16px;
    font-size: 14px;
}

.btn.ghost {
    color: #cacaca;
    border: 1px solid #cacaca;
}

.btn.refund {
    color: #6e6e6e;
    border: 1px solid #6e6e6e;
}

.btn.primary {
    border: 1px solid #ff8000;
    color: #ff8000;
}

.empty,
.loading {
    text-align: center;
    color: #999;
    padding: 30px 0;
}
</style>